package server;

import mapper.MyContext;
import mapper.MyHost;
import mapper.MyMapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;
import java.util.Objects;

public class RequestProcessor extends Thread {

    private Socket socket;
    private MyMapper myMapper;

    public RequestProcessor(Socket socket, MyMapper myMapper) {
        this.socket = socket;
        this.myMapper = myMapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            MyHost myHost = myMapper.getMyHost();
            String appBase = myMapper.getAppBase();
            // 应用名称定义
            String url = request.getUrl();
            String contextName = url.split("/")[1];
            MyContext myContext = myHost.getMyContextMap().get(contextName);
            if (Objects.isNull(myContext)){
                response.output(HttpProtocolUtil.getHttpHeader404());
                socket.close();
                return;
            }

            // 静态资源处理
            if(myContext.getMyWrapperMap().get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl(),appBase);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = (HttpServlet) myContext.getMyWrapperMap().get(request.getUrl()).getServlet();
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
